<template>
  <div class="card">
    <h2 class="text-2xl font-bold mb-4">用户管理</h2>
    
    <div v-if="loading" class="flex justify-content-center">
      <ProgressSpinner />
    </div>
    
    <div v-else-if="error" class="p-4 bg-red-100 text-red-700 border-round mb-4">
      {{ error }}
    </div>
    
    <div v-else>
      <DataTable :value="users" :paginator="true" :rows="10" 
                 paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink RowsPerPageDropdown"
                 :rowsPerPageOptions="[5,10,25]" responsiveLayout="scroll">
        <Column field="id" header="ID" sortable></Column>
        <Column field="username" header="用户名" sortable></Column>
        <Column field="email" header="邮箱" sortable></Column>
        <Column field="is_active" header="状态">
          <template #body="{data}">
            <Tag :severity="data.is_active ? 'success' : 'danger'" 
                 :value="data.is_active ? '激活' : '禁用'"></Tag>
          </template>
        </Column>
        <Column field="created_at" header="创建时间" sortable>
          <template #body="{data}">
            {{ new Date(data.created_at).toLocaleString() }}
          </template>
        </Column>
        <Column header="操作">
          <template #body="{data}">
            <Button icon="pi pi-user-edit" class="p-button-text p-button-rounded" 
                    @click="editUser(data)" tooltip="编辑用户" />
            <Button icon="pi pi-trash" class="p-button-text p-button-rounded p-button-danger" 
                    @click="confirmDeleteUser(data)" tooltip="删除用户" />
          </template>
        </Column>
      </DataTable>
    </div>
    
    <!-- 用户编辑对话框 -->
    <Dialog v-model:visible="userDialog" header="用户信息" :style="{width: '450px'}" modal>
      <div class="p-fluid">
        <div class="field mb-4">
          <label for="username">用户名</label>
          <InputText id="username" v-model="editingUser.username" required autofocus />
        </div>
        <div class="field mb-4">
          <label for="email">邮箱</label>
          <InputText id="email" v-model="editingUser.email" required />
        </div>
        <div class="field mb-4">
          <label for="status">状态</label>
          <ToggleButton v-model="editingUser.is_active" onLabel="激活" offLabel="禁用" />
        </div>
      </div>
      <template #footer>
        <Button label="取消" icon="pi pi-times" class="p-button-text" @click="userDialog = false" />
        <Button label="保存" icon="pi pi-check" @click="saveUser" />
      </template>
    </Dialog>
    
    <!-- 删除确认对话框 -->
    <ConfirmDialog></ConfirmDialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { useConfirm } from 'primevue/useconfirm';
import { useToast } from 'primevue/usetoast';
import axios from 'axios';

// PrimeVue组件
import DataTable from 'primevue/datatable';
import Column from 'primevue/column';
import Button from 'primevue/button';
import Dialog from 'primevue/dialog';
import InputText from 'primevue/inputtext';
import ToggleButton from 'primevue/togglebutton';
import ProgressSpinner from 'primevue/progressspinner';
import Tag from 'primevue/tag';
import ConfirmDialog from 'primevue/confirmdialog';

interface User {
  id: number;
  username: string;
  email: string;
  is_active: boolean;
  created_at: string;
  updated_at: string;
}

const users = ref<User[]>([]);
const loading = ref(true);
const error = ref('');
const userDialog = ref(false);
const confirm = useConfirm();
const toast = useToast();

const editingUser = reactive({
  id: 0,
  username: '',
  email: '',
  is_active: true
});

onMounted(async () => {
  await fetchUsers();
});

async function fetchUsers() {
  loading.value = true;
  error.value = '';
  
  try {
    const response = await axios.get('/api/users');
    users.value = response.data;
  } catch (err: any) {
    error.value = '获取用户列表失败: ' + (err.response?.data?.message || err.message);
    console.error(err);
  } finally {
    loading.value = false;
  }
}

function editUser(user: User) {
  editingUser.id = user.id;
  editingUser.username = user.username;
  editingUser.email = user.email;
  editingUser.is_active = user.is_active;
  userDialog.value = true;
}

async function saveUser() {
  try {
    await axios.put(`/api/users/${editingUser.id}`, editingUser);
    await fetchUsers();
    userDialog.value = false;
    toast.add({ severity: 'success', summary: '成功', detail: '用户信息已更新', life: 3000 });
  } catch (err: any) {
    toast.add({ severity: 'error', summary: '错误', detail: err.response?.data?.message || '更新失败', life: 3000 });
  }
}

function confirmDeleteUser(user: User) {
  confirm.require({
    message: `确定要删除用户 "${user.username}" 吗?`,
    header: '删除确认',
    icon: 'pi pi-exclamation-triangle',
    acceptLabel: '是',
    rejectLabel: '否',
    accept: () => deleteUser(user.id)
  });
}

async function deleteUser(id: number) {
  try {
    await axios.delete(`/api/users/${id}`);
    await fetchUsers();
    toast.add({ severity: 'success', summary: '成功', detail: '用户已删除', life: 3000 });
  } catch (err: any) {
    toast.add({ severity: 'error', summary: '错误', detail: err.response?.data?.message || '删除失败', life: 3000 });
  }
}
</script>